'use client';

import { useState, useRef, useEffect } from 'react';
import { useActivate, useUnactivate } from 'react-activation';

// 表单值接口
interface FormValues {
  // 个人资料
  profileName: string;
  profileEmail: string;
  profilePhone: string;
  profileBio: string;
  
  // 系统设置
  systemName: string;
  cacheTime: number;
  pageSize: string;
  debugMode: boolean;
  
  // 通知设置
  notifySystem: boolean;
  notifyProduct: boolean;
  notifyOrder: boolean;
  notifyMarketing: boolean;
  
  // 外观设置
  theme: 'light' | 'dark' | 'system';
  fontSize: number;
  primaryColor: string;
}

export default function SettingsPage() {
  // 使用useRef保存表单状态，这样在组件重新渲染时不会丢失
  const formValuesRef = useRef<FormValues>({
    // 个人资料默认值
    profileName: '测试用户',
    profileEmail: 'test@example.com',
    profilePhone: '13800138000',
    profileBio: '这是一个测试账号，用于演示系统功能。',
    
    // 系统设置默认值
    systemName: 'Next.js 管理系统',
    cacheTime: 30,
    pageSize: '20',
    debugMode: false,
    
    // 通知设置默认值
    notifySystem: true,
    notifyProduct: true,
    notifyOrder: true,
    notifyMarketing: false,
    
    // 外观设置默认值
    theme: 'light',
    fontSize: 3,
    primaryColor: 'blue'
  });

  // 内部标签状态，不依赖于URL
  const [activeTab, setActiveTab] = useState('profile');
  
  // 表单状态，使用useRef的值初始化
  const [formValues, setFormValues] = useState<FormValues>(formValuesRef.current);
  
  // 当组件被激活（从缓存中恢复）时触发
  useActivate(() => {
    console.log('设置页面被激活', activeTab);
  });
  
  // 当组件被停用（进入缓存）时触发
  useUnactivate(() => {
    console.log('设置页面被缓存', activeTab);
  });

  // 保存表单值的变化到ref中
  useEffect(() => {
    formValuesRef.current = formValues;
  }, [formValues]);

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value, type } = e.target;
    setFormValues(prev => ({
      ...prev,
      [name]: type === 'checkbox' 
        ? (e.target as HTMLInputElement).checked 
        : type === 'number' 
          ? Number(value)
          : value
    }));
  };

  // 处理主题选择
  const handleThemeChange = (theme: 'light' | 'dark' | 'system') => {
    setFormValues(prev => ({
      ...prev,
      theme
    }));
  };

  // 处理颜色选择
  const handleColorChange = (color: string) => {
    setFormValues(prev => ({
      ...prev,
      primaryColor: color
    }));
  };

  // 保存设置
  const handleSaveSettings = (settingType: string) => {
    // 这里只是模拟，实际应用中会将数据保存到后端
    console.log(`保存${settingType}设置:`, formValues);
    alert(`${settingType}设置已保存！`);
  };

  return (
    <div className="p-6">
      <h1 className="text-2xl font-semibold mb-6">系统设置</h1>
      
      <div className="flex flex-col md:flex-row gap-6">
        {/* 左侧设置标签页 */}
        <div className="w-full md:w-64 bg-white rounded-lg shadow overflow-hidden">
          <nav className="p-2">
            <button 
              onClick={() => setActiveTab('profile')}
              className={`w-full text-left py-2 px-3 rounded mb-1 ${
                activeTab === 'profile' ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-50'
              }`}
            >
              个人资料
            </button>
            <button 
              onClick={() => setActiveTab('account')}
              className={`w-full text-left py-2 px-3 rounded mb-1 ${
                activeTab === 'account' ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-50'
              }`}
            >
              账号安全
            </button>
            <button 
              onClick={() => setActiveTab('notification')}
              className={`w-full text-left py-2 px-3 rounded mb-1 ${
                activeTab === 'notification' ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-50'
              }`}
            >
              通知设置
            </button>
            <button 
              onClick={() => setActiveTab('appearance')}
              className={`w-full text-left py-2 px-3 rounded mb-1 ${
                activeTab === 'appearance' ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-50'
              }`}
            >
              外观设置
            </button>
            <button 
              onClick={() => setActiveTab('system')}
              className={`w-full text-left py-2 px-3 rounded ${
                activeTab === 'system' ? 'bg-blue-50 text-blue-600' : 'hover:bg-gray-50'
              }`}
            >
              系统参数
            </button>
          </nav>
        </div>
        
        {/* 右侧设置内容 - 保持内容始终在DOM中，只是通过CSS显示/隐藏 */}
        <div className="flex-1 bg-white rounded-lg shadow p-6">
          <div style={{ display: activeTab === 'profile' ? 'block' : 'none' }}>
            <h2 className="text-lg font-medium mb-4">个人资料</h2>
            <div className="mb-6 flex flex-col sm:flex-row items-start sm:items-center gap-4">
              <div className="w-24 h-24 bg-gray-200 rounded-full flex items-center justify-center">
                <span className="text-gray-400">头像</span>
              </div>
              <button className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600">
                更新头像
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <input 
                  type="text" 
                  name="profileName"
                  value={formValues.profileName}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                <input 
                  type="email" 
                  name="profileEmail"
                  value={formValues.profileEmail}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">电话</label>
                <input 
                  type="tel" 
                  name="profilePhone"
                  value={formValues.profilePhone}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">个人简介</label>
                <textarea 
                  name="profileBio"
                  value={formValues.profileBio}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                  rows={4}
                />
              </div>
              <div className="pt-4">
                <button 
                  className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
                  onClick={() => handleSaveSettings('个人资料')}
                >
                  保存更改
                </button>
              </div>
            </div>
          </div>
          
          <div style={{ display: activeTab === 'account' ? 'block' : 'none' }}>
            <h2 className="text-lg font-medium mb-4">账号安全</h2>
            <div className="space-y-6">
              <div>
                <h3 className="text-md font-medium mb-3">修改密码</h3>
                <div className="space-y-3">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">当前密码</label>
                    <input 
                      type="password" 
                      className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                    <input 
                      type="password" 
                      className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                    <input 
                      type="password" 
                      className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                    />
                  </div>
                  <div className="pt-2">
                    <button 
                      className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
                      onClick={() => handleSaveSettings('密码')}
                    >
                      更新密码
                    </button>
                  </div>
                </div>
              </div>
              
              <div className="pt-4 border-t">
                <h3 className="text-md font-medium mb-3">双因素认证</h3>
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">启用双因素认证以提高账号安全性</p>
                    <p className="text-xs text-gray-500 mt-1">当前状态：未启用</p>
                  </div>
                  <button className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600">
                    启用
                  </button>
                </div>
              </div>
              
              <div className="pt-4 border-t">
                <h3 className="text-md font-medium mb-3 text-red-600">删除账号</h3>
                <p className="text-sm text-gray-600 mb-3">删除账号后，您的所有数据将被永久删除且无法恢复</p>
                <button className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600">
                  删除我的账号
                </button>
              </div>
            </div>
          </div>
          
          <div style={{ display: activeTab === 'notification' ? 'block' : 'none' }}>
            <h2 className="text-lg font-medium mb-4">通知设置</h2>
            <div className="space-y-4">
              <div className="flex items-center justify-between py-3 border-b">
                <div>
                  <h3 className="font-medium">系统通知</h3>
                  <p className="text-sm text-gray-500">接收系统更新和维护相关通知</p>
                </div>
                <div className="flex items-center">
                  <label className="inline-flex items-center cursor-pointer">
                    <input 
                      type="checkbox" 
                      name="notifySystem"
                      checked={formValues.notifySystem}
                      onChange={handleInputChange}
                      className="sr-only peer" 
                    />
                    <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              </div>
              <div className="flex items-center justify-between py-3 border-b">
                <div>
                  <h3 className="font-medium">产品更新</h3>
                  <p className="text-sm text-gray-500">接收产品库存和价格变动通知</p>
                </div>
                <div className="flex items-center">
                  <label className="inline-flex items-center cursor-pointer">
                    <input 
                      type="checkbox" 
                      name="notifyProduct"
                      checked={formValues.notifyProduct}
                      onChange={handleInputChange}
                      className="sr-only peer" 
                    />
                    <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              </div>
              <div className="flex items-center justify-between py-3 border-b">
                <div>
                  <h3 className="font-medium">订单状态</h3>
                  <p className="text-sm text-gray-500">接收订单状态变更通知</p>
                </div>
                <div className="flex items-center">
                  <label className="inline-flex items-center cursor-pointer">
                    <input 
                      type="checkbox" 
                      name="notifyOrder"
                      checked={formValues.notifyOrder}
                      onChange={handleInputChange}
                      className="sr-only peer" 
                    />
                    <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              </div>
              <div className="flex items-center justify-between py-3 border-b">
                <div>
                  <h3 className="font-medium">营销信息</h3>
                  <p className="text-sm text-gray-500">接收优惠活动和促销信息</p>
                </div>
                <div className="flex items-center">
                  <label className="inline-flex items-center cursor-pointer">
                    <input 
                      type="checkbox" 
                      name="notifyMarketing"
                      checked={formValues.notifyMarketing}
                      onChange={handleInputChange}
                      className="sr-only peer" 
                    />
                    <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                  </label>
                </div>
              </div>
              <div className="pt-4">
                <button 
                  className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
                  onClick={() => handleSaveSettings('通知')}
                >
                  保存设置
                </button>
              </div>
            </div>
          </div>
          
          <div style={{ display: activeTab === 'appearance' ? 'block' : 'none' }}>
            <h2 className="text-lg font-medium mb-4">外观设置</h2>
            <div className="space-y-6">
              <div>
                <h3 className="text-md font-medium mb-3">主题</h3>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  <div 
                    className={`border rounded-lg p-3 bg-white cursor-pointer ${formValues.theme === 'light' ? 'ring-2 ring-blue-500' : ''}`}
                    onClick={() => handleThemeChange('light')}
                  >
                    <div className="h-20 bg-white border rounded mb-2"></div>
                    <div className="text-center">亮色主题</div>
                  </div>
                  <div 
                    className={`border rounded-lg p-3 bg-white cursor-pointer ${formValues.theme === 'dark' ? 'ring-2 ring-blue-500' : ''}`}
                    onClick={() => handleThemeChange('dark')}
                  >
                    <div className="h-20 bg-gray-800 border rounded mb-2"></div>
                    <div className="text-center">暗色主题</div>
                  </div>
                  <div 
                    className={`border rounded-lg p-3 bg-white cursor-pointer ${formValues.theme === 'system' ? 'ring-2 ring-blue-500' : ''}`}
                    onClick={() => handleThemeChange('system')}
                  >
                    <div className="h-20 bg-gradient-to-r from-white to-gray-800 border rounded mb-2"></div>
                    <div className="text-center">跟随系统</div>
                  </div>
                </div>
              </div>
              
              <div className="pt-4 border-t">
                <h3 className="text-md font-medium mb-3">字体大小</h3>
                <div className="flex items-center">
                  <span className="text-sm mr-3">A</span>
                  <input 
                    type="range" 
                    name="fontSize"
                    min="1" 
                    max="5" 
                    value={formValues.fontSize}
                    onChange={handleInputChange}
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                  />
                  <span className="text-xl ml-3">A</span>
                </div>
              </div>
              
              <div className="pt-4 border-t">
                <h3 className="text-md font-medium mb-3">主色调</h3>
                <div className="grid grid-cols-6 gap-2">
                  <button 
                    className={`w-8 h-8 rounded-full bg-blue-500 ${formValues.primaryColor === 'blue' ? 'ring-2 ring-black' : ''}`}
                    onClick={() => handleColorChange('blue')}
                  ></button>
                  <button 
                    className={`w-8 h-8 rounded-full bg-green-500 ${formValues.primaryColor === 'green' ? 'ring-2 ring-black' : ''}`}
                    onClick={() => handleColorChange('green')}
                  ></button>
                  <button 
                    className={`w-8 h-8 rounded-full bg-red-500 ${formValues.primaryColor === 'red' ? 'ring-2 ring-black' : ''}`}
                    onClick={() => handleColorChange('red')}
                  ></button>
                  <button 
                    className={`w-8 h-8 rounded-full bg-purple-500 ${formValues.primaryColor === 'purple' ? 'ring-2 ring-black' : ''}`}
                    onClick={() => handleColorChange('purple')}
                  ></button>
                  <button 
                    className={`w-8 h-8 rounded-full bg-yellow-500 ${formValues.primaryColor === 'yellow' ? 'ring-2 ring-black' : ''}`}
                    onClick={() => handleColorChange('yellow')}
                  ></button>
                  <button 
                    className={`w-8 h-8 rounded-full bg-gray-500 ${formValues.primaryColor === 'gray' ? 'ring-2 ring-black' : ''}`}
                    onClick={() => handleColorChange('gray')}
                  ></button>
                </div>
              </div>
              
              <div className="pt-4">
                <button 
                  className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
                  onClick={() => handleSaveSettings('外观')}
                >
                  应用设置
                </button>
              </div>
            </div>
          </div>
          
          <div style={{ display: activeTab === 'system' ? 'block' : 'none' }}>
            <h2 className="text-lg font-medium mb-4">系统参数</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">系统名称</label>
                <input 
                  type="text" 
                  name="systemName"
                  value={formValues.systemName}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">系统版本</label>
                <input 
                  type="text" 
                  className="w-full px-3 py-2 border rounded-md bg-gray-50" 
                  value="v1.0.0"
                  readOnly
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">数据缓存时间 (分钟)</label>
                <input 
                  type="number" 
                  name="cacheTime"
                  value={formValues.cacheTime}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 
                  min="1"
                  max="1440"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">每页显示记录数</label>
                <select 
                  name="pageSize"
                  value={formValues.pageSize}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="10">10条/页</option>
                  <option value="20">20条/页</option>
                  <option value="50">50条/页</option>
                  <option value="100">100条/页</option>
                </select>
              </div>
              <div className="flex items-center mt-4">
                <input 
                  type="checkbox"
                  id="debug-mode"
                  name="debugMode"
                  checked={formValues.debugMode}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500" 
                />
                <label htmlFor="debug-mode" className="ml-2 text-sm font-medium text-gray-700">
                  启用调试模式
                </label>
              </div>
              <div className="pt-4">
                <button 
                  className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 mr-2"
                  onClick={() => handleSaveSettings('系统')}
                >
                  保存设置
                </button>
                <button 
                  className="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600"
                  onClick={() => {
                    setFormValues({
                      ...formValuesRef.current,
                      systemName: 'Next.js 管理系统',
                      cacheTime: 30,
                      pageSize: '20',
                      debugMode: false
                    });
                  }}
                >
                  恢复默认
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 